from pydantic import BaseModel
from fastapi import APIRouter, Request
from utils import db_pool, token_required

router = APIRouter()


class Add_Tracks_model(BaseModel):
    tag: str
    data: list


class Add_Address_model(BaseModel):
    mark: str
    x: float
    y: float


class Query_Visible_Address_model(BaseModel):
    left_bottom: list
    right_top: list


class Query_Address_model(BaseModel):
    tag: str


class Opr_Address_model(BaseModel):
    ids: list


@router.post('/TracksAdd')
@token_required
def add_tracks(data: Add_Tracks_model, req: Request):
    sql_select = "select id from coordinate_key where tag=%s order by id desc limit 0,1;"
    res = db_pool.query(sql_select, (data.tag,))
    if len(res) < 1:
        sql_ins_key = "INSERT INTO coordinate_key(tag) VALUES (%s);"
        execute_result = db_pool.execute_sql(sql_ins_key, (data.tag,))
        print("执行结果:", execute_result)
    _id = db_pool.query(sql_select, (data.tag,))[0]["id"]
    sql_head = "INSERT INTO coordinate_value(id, x, y) VALUES\n"
    sql_value = []
    for i in data.data:
        sql_head += "(%s, %s, %s),\n"
        sql_value += [_id, i[0], i[1]]
    execute_result = db_pool.execute_sql(sql_head[:-2] + ";", tuple(sql_value))
    print("执行结果:", execute_result)
    return {"status": True}


@router.post('/AddressAdd')
@token_required
def add_address(data: Add_Address_model, req: Request):
    sql = "INSERT INTO address_collect(mark, x, y) VALUES (%s, %s, %s);"
    execute_result = db_pool.execute_sql(sql, (data.mark, data.x, data.y))
    print("执行结果:", execute_result)
    return {"status": True}


@router.post('/VisibleAddressQuery')
@token_required
def query_visible_address(data: Query_Visible_Address_model, req: Request):
    sql = "select mark, x, y from address_collect "
    sql += "where %s <= x and x <= %s "
    sql += "and %s <= y and y <= %s and status='A';"
    res = db_pool.query(sql, (data.left_bottom[0], data.right_top[0], data.left_bottom[1], data.right_top[1]))
    return {"status": True, "data": res}


@router.post('/AddressQuery')
@token_required
def query_address(data: Query_Address_model, req: Request):
    sql = "select id, mark, x, y from address_collect where status in ('A', 'H');"
    res = db_pool.query(sql, (data.left_bottom[0], data.right_top[0], data.left_bottom[1], data.right_top[1]))
    return {"status": True, "data": res}


def hide_or_delete_address(opr, ids):
    where = ",".join("%s" * len(ids))
    sql = f"update address_collect set status='{opr}' where id in ({where});"
    execute_result = db_pool.execute_sql(sql, tuple(ids))
    print("执行结果:", execute_result)
    return {"status": True}


@router.post('/AddressHide')
@token_required
def hide_address(data: Opr_Address_model, req: Request):
    return hide_or_delete_address("H", data.ids)


@router.post('/AddressDelete')
@token_required
def delete_address(data: Opr_Address_model, req: Request):
    return hide_or_delete_address("D", data.ids)
